package com.sh4.controller;


import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.sh4.entity.User; 
import com.sh4.service.UserRegisteService;
import com.sh4.util.Sh4Utils;

import net.sf.json.JSONObject;

@RestController
@RequestMapping(value = "user" , method = RequestMethod.POST)
public class RegisterController {
	
	@Autowired
	UserRegisteService userService;
	

	@RequestMapping(value = "/login")
	public Map<String , Object> login(@RequestBody JSONObject reqBody,HttpSession session){
		Map<String , Object> result = new HashMap<String , Object>();
		int status = 200;
		String msg = "登录成功";
		
		String userCode = reqBody.getString("userCode");
		String password = reqBody.getString("password");
		String roleId = reqBody.getString("roleId");
		
		User user = userService.findUser(userCode);
		if(user == null){
			status = 300;
			msg = "暂未查到用户信息";
		}else{
			try {
				String saltPassword = Sh4Utils.getSha1(password+user.getSalt());
				if(!saltPassword.equals(user.getPassword())){
					status = 300;
					msg = "用户密码不正确";
					
				}else{
					
					Map<String , Object> userInfo = userService.getUserInfo(userCode, roleId);
					if(userInfo == null) {
						status = 300;
						msg = "暂未查到用户相关角色信息";
					}else {
						result.put("user", userInfo);
						session.setAttribute("userCode", user);
						session.setAttribute("roleId", roleId);
					}
				}
				
			} catch (Exception e) {
				status = 300;
				msg = "内部错误";
			}

		}
		
		result.put("status", status);
		result.put("msg", msg);
		
		return result;
	}

	@RequestMapping(value = "outLogin",method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> outLogin(@RequestBody JSONObject object,HttpSession session) {
		
		Map<String, Object> result = new HashMap<String,Object>();
		int status = 200;
		
		session.invalidate();
		
		result.put("status", status);
		return result;
	}
	@RequestMapping(value = "code" , method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> validatorUserCode(@RequestBody JSONObject object) {
		Map<String, Object> result = new HashMap<String,Object>();
		int status = 200;
		String msg = "请求成功";
		String userCode = object.getString("userCode");
		User user = userService.findUser(userCode);
		if (user == null) {
			status = 404;
			msg = "没有此用户名";
		}
		result.put("status", status);
		result.put("msg", msg);
		
		return result;
	}
	
}
